package com.ttmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ttmall.common.pojo.EasyUIDataGridResult;
import com.ttmall.common.pojo.TaotaoResult;
import com.ttmall.mapper.TbContentMapper;
import com.ttmall.pojo.TbContent;
import com.ttmall.pojo.TbContentExample;
import com.ttmall.service.ContentCategoryService;
import com.ttmall.service.ContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by GalaIO on 2018/1/18.
 */
@Service
public class ContentServiceImpl implements ContentService {

    @Autowired
    private TbContentMapper tbContentMapper;

    @Override
    public EasyUIDataGridResult listContentByContentCatId(Long categoryId, Integer pages, Integer row) {
        PageHelper.startPage(pages, row);

        TbContentExample example = new TbContentExample();
        TbContentExample.Criteria criteria = example.createCriteria();
        criteria.andCategoryIdEqualTo(categoryId);
        List<TbContent> tbContents = tbContentMapper.selectByExample(example);

        PageInfo<TbContent> pageInfo = new PageInfo<TbContent>(tbContents);

        return EasyUIDataGridResult.build(pageInfo.getTotal(), tbContents);
    }

    @Override
    public TaotaoResult insertContent(TbContent tbContent) {
        Date now = new Date();
        tbContent.setCreated(now);
        tbContent.setUpdated(now);
        tbContentMapper.insert(tbContent);
        return TaotaoResult.ok();
    }

    @Override
    public TaotaoResult updateContent(TbContent tbContent) {
        Date now = new Date();
        tbContent.setUpdated(now);
        tbContentMapper.updateByPrimaryKeySelective(tbContent);
        return TaotaoResult.ok();
    }

    @Override
    public TaotaoResult deleteContent(List<Long> ids) {
        TbContentExample example = new TbContentExample();
        TbContentExample.Criteria criteria = example.createCriteria();
        criteria.andIdIn(ids);
        tbContentMapper.deleteByExample(example);
        return TaotaoResult.ok();
    }

    @Override
    public TaotaoResult getContentById(Long id) {
        TbContentExample example = new TbContentExample();
        TbContentExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(id);
        List<TbContent> tbContents = tbContentMapper.selectByExampleWithBLOBs(example);
        if (tbContents != null && tbContents.size() > 0) {
            return TaotaoResult.ok(tbContents.get(0));
        }
        return TaotaoResult.ok();
    }
}
